package ltd.yangyh.controller;

import ltd.yangyh.bean.Book;
import ltd.yangyh.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class RouteController {
    @Resource
    private BookService bookService;

    @GetMapping("/")
    public String bookList(Model model) {
        model.addAttribute("bookList", bookService.getAllBook());
        return "bookList";
    }

    @GetMapping("/test")
    @ResponseBody
    public Book test() {
        Book book = new Book();
        book.setBookId(1);
        book.setBookCount("30");
        book.setBookDetail("唐磊");
        return book;
    }

    @GetMapping("/addBook")
    public String addBookPage() {
        return "addBook";
    }

    @PostMapping("/addBook")
    public String addBook(Book book) {
        System.out.println("进入addBook Post");
        System.out.println(book);
        bookService.addBook(book);
        return "redirect:/";
    }

    @GetMapping("/updateBook")
    public String updateBookPage(Integer id, Model model) {
        Book book = bookService.QueryBookById(id);
        System.out.println("------>" + book);
        model.addAttribute("book", book);
        return "updateBook";
    }

    @PostMapping("/updateBook")
    public String updateBook(Book book) {
        bookService.updateBookById(book);
        return "redirect:/";
    }

    @GetMapping("/deleteBook")
    public String deleteBook(Integer id) {
        bookService.deleteBookById(id);
        return "redirect:/";
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
        if (username.equals("admin") && password.equals("admin")) {
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            return "redirect:/";
        }
        return "redirect:/login";
    }
}
